#!/bin/bash
#
# This script requires lcov to be installed
#

TESTS="\
 test_encode \
 test_io \
 test_parcel \
 test_request \
 test_transport"

FLAVOR="coverage"

function require() {
    if ! which $1 >> /dev/null ; then
        echo "*** Please install $1 first!"
        exit 1
    fi
}

# Check required tools
require lcov
require dirname
require realpath

# LCOV 1.10 has branch coverage disabled per default
# Previous versions didn't have the --rc option
if  [ ! -z "$(lcov --help | grep ' --rc ')" ] ; then
    LCOV_OPT="--rc lcov_branch_coverage=1"
    GENHTML_OPT="--branch-coverage"
fi

COV_DIR=$(realpath "$(dirname $0)")
TEST_DIR=$(realpath "${COV_DIR}/..")
BASE_DIR=$(realpath "${TEST_DIR}/..")

export LIBRARY_PATH="$BASE_DIR/build/$FLAVOR"

make -C "$BASE_DIR" clean $FLAVOR
for t in $TESTS ; do
    pushd "$TEST_DIR/$t"
    make -C "$TEST_DIR/$t" clean $FLAVOR || exit 1
    build/$FLAVOR/$t || exit 1
    popd
done

FULL_COV="$COV_DIR/full.gcov"
GRILIO_COV="$COV_DIR/libgrilio.gcov"
rm -f "$FULL_COV" "$GRILIO_COV"
lcov $LCOV_OPT -c -d "$LIBRARY_PATH" -b "$BASE_DIR" -o "$FULL_COV" || exit 1
lcov $LCOV_OPT -e "$FULL_COV" "$BASE_DIR/src/*" -o "$GRILIO_COV" || exit 1
genhtml $GENHTML_OPT -t libgrilio "$GRILIO_COV" --output-directory "$COV_DIR/report" || exit 1
